<template>
  <Modal v-model="visible" @on-visible-change="changeModal" title="批量导入" :width="width">
    <Form :label-width="80" :model="form" ref="form">
      <Row>
        <Col :md="23">
          <FormItem label="选择文件" :error="errormsg">
            <div class="fileInput" @click="fileClick">
              <Input v-model="fileName" :readonly="true" placeholder="请选择文件"></Input>
              <Button type='primary'>选择文件</Button>
              <input ref="fileinput" accept=".xlsx" :value="fileName" type="file" @change="changeFile" style="width:100%" />
            </div>
          </FormItem>
        </Col>
      </Row>
      <div class="resdiv" v-if="isResponse">
        成功导入 {{response.right}} 个，失败 {{response.error}} 个 ,合计 {{response.total}} 个，<a v-if="response.path" @click="downloadError(response.path)">下载错误Excel</a>
      </div>
    </Form>
    <div slot="footer">
      <Button type="text" @click="close">取消</Button>
      <Button type="primary" @click="submit">导入</Button>
    </div>
  </Modal>
</template>

<script>
  import {post}  from '@/util/request'

  export default {
    props:{
      value:{type:Boolean},
      submitPath:{type:String,required:true},
      width:{type:Number,defautl:400}
    },
    data(){
      return {
        visible:this.value,
        isLoading:false,

        form:{},
        fileName:'',
        errormsg:'',
        isResponse:false,
        response:{},
      };
    },
    watch:{
      value(v){
        this.visible = v;
      },
      visible(v){
        this.$emit('input',v);
      }
    },
    computed:{

    },
    methods:{
      close(){
        this.visible = false;
      },
      changeModal(v){
        if (!v){
          this.isResponse = false;
					this.response = {};
					this.form = {};
					this.fileName = '';
					this.errormsg = '';
        }
      },
      fileClick(){
        this.$refs.fileinput.click();
      },
      changeFile(v){
        this.errormsg = '';
				this.isResponse = false;
				this.response = {};
				this.form.upload = v.target.files[0];
				this.fileName = v.target.value;
      },
      async submit(){
        if(this.form.upload){
          this.isLoading = true;
					let res = await post(this.submitPath,{...this.form});
          this.isLoading = false;

					this.response = res.data.data;
					this.isResponse = true;
          if (this.response.right > 0) this.$emit('on-success');
          if (this.response.error === 0) return this.$Message.success('导入成功');
          if (this.response.error > 0 && this.response.right > 0) return this.$Message.warning('部分数据导入失败');
          if (this.response.error > 0 && this.response.right === 0) return this.$Message.error('导入失败');
				}else{
					this.errormsg = "必须选择文件"
				}
      },
      downloadError(url){
        window.location.href = url;
      }
    }
  }
</script>
